/***
This client is for demonstration purposes only!
Please see https://code.google.com/p/tvkaista-api/ for further information.

Copyright 2012 TVkaista
Licensed under New BSD License
***/

/// Collections can be discovered by looking for the atom:link[rel='edit'] 
/// element in a channel element
var collections = { 'season passes' : 'http://www.tvkaista.fi/feed/seasonpasses/',
                    'playlist' : 'http://www.tvkaista.fi/feed/playlist/'};

// Display a warning for browsers that may not work
$(document).ready(function() {
  if ((!$.browser.chrome && !$.browser.mozilla) 
       || parseInt(!$.browser.version, 10) < 17) {
       $('#content').html("<b>WARNING: This client has only been tested on "
                        + "recent versions of Chrome and Firefox and "
			+ "may not work correctly on your browser.</b>");
  }
});

// Set the HTTP User-Agent header or an alternative X-User-Agent header on 
// all requests to the feed so that the client can be identified server-side
$.ajaxSetup({
  beforeSend: function(request) {
    request.setRequestHeader("User-Agent","ReferenceJsImplementation/0.1");
    request.setRequestHeader("X-User-Agent","ReferenceJsImplementation/0.1");
  }
});

// Inform the user of any errors so that they can diagnose and report problems
function fail(jqXHR, status, error) {
    $('#content').html("Could not access " + this.url 
                       + ": status=" + status + " error=" + error);
}

// Handle the mediaRSS contents
/// Note: This client uses jquery selectors to navigate the XML structure.
///       Similar functionality is available in XPath libraries on
///       most platforms.
function handle(xml) {    
    var mediaNs = 'media\\:';
    var dcNs = 'dc\\:';
    var atomNs = 'atom\\:';
    if ($.browser.chrome) {
      // Platform-specific incompatability: Chrome strips namespaces from XML
      mediaNs = '';
      dcNs = '';
      atomNs = '';
    }
		
    // Select the (first) channel, which is a child of the top element 'rss'
    /// The channel contains all RSS items and describes the RSS collection
    var channel = $(xml).find('rss > channel:first');
    // Select the (first) title element of the channel and store the containing text
    var channelTitle = $(channel).find('title:first').text();
    // Display the channel title to the user
    $('#content').html(channelTitle);
    
    // Find atom:links with specific rel attributes in the channel element and store
    // their href attributes (Hypertext REFerences)
    /// These only exist in archived feeds and are defined in RFC5005
    var curArchive = $(channel).find(atomNs+"link[rel='current']").attr('href');
    var prevArchive = $(channel).find(atomNs+"link[rel='prev-archive']").attr('href');
    var nextArchive = $(channel).find(atomNs+"link[rel='next-archive']").attr('href');
    
    // Display action links to the user if any archive links were defined in the feed.
    if (prevArchive) {
      var link = $("<div class='action'>").text('Previous archive').click(function() {
        get(prevArchive);
      });
      $('#content').append(link);
    }
    if (curArchive) {
      var link = $("<div class='action'>").text('Current archive').click(function() {
        get(curArchive);
      });
      $('#content').append(link);
    }
    if (nextArchive) {
      var link = $("<div class='action'>").text('Next archive').click(function() {
        get(nextArchive);
      });
      $('#content').append(link);
    }
    
    // Select all RSS items in the channel and perform the following function on each one
    $(channel).find('item').each(function() {
        // The item's title and link are defined in the title and link elements.
        var item_title = $(this).find('title:first').text();
        var item_link = $(this).find('link:first').text();
	// Ignore templated links for now (search)
	if (item_link.indexOf('{') !== -1) return;

        var element;
	// Attempt to select the mediaRSS media:group, a collection of media pertaining
	// to the item.
        var media = $(this).find(mediaNs+'group');
        if (media.length == 0) {
	    // This is not a media item. Display the item's link to the user
            element = $("<div class='button'>").text(item_title).click(function() {
                get(item_link);
            });
        } else {
	    // Gather the program data for this media item
            element = $("<div class='program'>");
	    // Get the air date for the program
            var date = $("<div class='date'>").text( new Date($(this).find(dcNs+'date').text()) );
	    // ..and display it to the user
            element.append(date);
	    // Get the first title in the media item. 
	    /// This is typically the same title as the previously defined 'item_title', but might
	    /// be localised and available in multiple languages (at some point).
            var title = $("<div class='title'>")
                .text( $(media).find(mediaNs+'title:first').text());
            element.append(title);
	    // Media item description
            var desc = $("<div class='description'>")
                .text( $(media).find(mediaNs+'description:first').text() );
            element.append(desc);
	    // Media item player link
            var link = $('<a>').text('Play')
                .attr('href', $(media).find(mediaNs+'player:first').attr('url'));
            element.append(link);
	    // Select all media:content elements and perform the following function on each one
            $(media).find(mediaNs+'content').each(function() {
	        // Display a download link to the user with bitrate and media-type details
                var link = $('<a>').text('Download ' + $(this).attr('bitrate') + 'kbps ' + $(this).attr('type'))
                    .attr('href', $(this).attr('url'));
                element.append(link);                  
            });
	    
	    // Add to <collection> links
	    var item = this; // Implementation-specific: Store a reference to the current item
	    // Perform the following function on each key:value in the 'collections' variable
	    $.each(collections, function(key, value) {
	      // Display links that add the current program/item to the collection
	      var link = $("<div class='action'>").text('Add to ' + key).click(function() {
	        // Post the guid(s) (or integer tvkaista:id(s)) that you want to add to the 
		// collection (playlist or season passes) to the collection url in the 'id'
		// parameter.
	        post(value, {id : $(item).find('guid').text()});
	      });
	      element.append(link);
	    });
        }        
	
	// Attempt to select the atom edit-link of an item
	var edit = $(this).find(atomNs+"link[rel='edit']").attr('href');
	if (edit !== undefined) {
	  // Display a link that removes the item if clicked
	  var rem = $("<div class='action'>").text('Remove').click(function() {
	    // Requesting a DELETE of the URL will remove it from its parent collection
	    /// The URL uniquely identifies the collection and item.
	    remove(edit);
	  });
	  element.append(rem);
	}
	$('#content').append(element);
    });
}

// Get the contents of an URL and return the output to the handle-function
function get(url) {    
    $.ajax({
        type : "GET", // HTTP method
// User credentials must be supplied using HTTP Basic Authentication	
// Note: This client uses the browser's built-in authentication system 
//      username : username,
//      password : password,
        url : url,
        dataType : "xml",
        xhrFields : { withCredentials: true },
        success : handle,
	error : fail});
}

// Post data to an URL and inform the user on success
function post(url, data) {    
    $.ajax({
        type : "POST", // HTTP method
// User credentials must be supplied using HTTP Basic Authentication	
/// Note: This client uses the browser's built-in authentication system 
//      username : username,
//      password : password,
        url : url,
	data : data,
        xhrFields : { withCredentials: true },
	success : function () {
	  alert('Recording added to collection');
	},
	error : fail});
}

// Request removal of a resource at an URL
function remove(url) {    
    $.ajax({
        type : "DELETE", // HTTP method
// User credentials must be supplied using HTTP Basic Authentication	
/// Note: This client uses the browser's built-in authentication system 
//      username : username,
//      password : password,
        url : url,
        xhrFields : { withCredentials: true },
	success : function() {
	  alert('Recording removed from collection');
	},
	error : fail});
}

